package com.czk.controller;

import com.alibaba.fastjson.JSONObject;
import com.czk.utlls.WeChatUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/8/2 11:22
 */
@Slf4j
@RestController
@RequestMapping("/wechat")
public class WeChatController {
    @Value("${appId}")
    private String appId;
    @Value("${secret}")
    private String secret;
    @Value("${tempUserUrl}")
    private String tempUserUrl;
    @Value("${getUnLookUpUserUrl}")
    private String getUnLookUpUserUrl;

    @SneakyThrows
    @GetMapping("/test")
    public void test(HttpServletRequest request, HttpServletResponse response) {
        /**
         * signature 微信加密签名
         * timestamp 时戳
         * nonce 随机数
         * echostr 随机字符串
         */
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        System.out.println(signature + "===" + timestamp + "===" + nonce + "===" + echostr);
        // 校验请求你是否来自微信
        if (WeChatUtil.check(timestamp, nonce, signature)) {
            log.info("验证成功");
            // 原样返回str
            PrintWriter printWriter = response.getWriter();
            //
            printWriter.print(echostr);
            printWriter.flush();
            printWriter.close();
            // 此时微信公众号平台会显示配置成功
        }
    }

    /**
     * 接收信息
     * 各种消息的类型的标签不一样
     *
     * @param request
     * @return
     */
    @PostMapping("/test")
    public void postTest(HttpServletRequest request, HttpServletResponse response) {
        log.info("【接收消息了】");
        try {
/*            ServletInputStream inputStream = request.getInputStream();
            // 读取消息
            byte[] bytes = new byte[1024];
            int len = 0;
            StringBuilder builder = new StringBuilder();
            while ((len = inputStream.read(bytes)) != -1) {
                builder.append(new String(bytes, 0, len));
            }
            *//**
             * <xml><ToUserName><![CDATA[gh_b1836e96d5e7]]></ToUserName>  开发者的微信号
             * <FromUserName><![CDATA[o365s57rVcua532rJ9zD2US518Wk]]></FromUserName> 发送者的微信号
             * <CreateTime>1627885001</CreateTime> 创建时间 整型，消单位是秒
             * <MsgType><![CDATA[text]]></MsgType> 消息类型
             * <Content><![CDATA[我爱你]]></Content> 消息内容
             * <MsgId>23305710850814890</MsgId> 消息id
             * </xml>
             *//*
            System.out.println(builder.toString());*/
            // 处理消息时间推送
            Map<String, String> map = WeChatUtil.parseRequest(request);
            System.out.println(map);
            // 回复消息
            response.setCharacterEncoding("utf-8");
            request.setCharacterEncoding("utf-8");
            /*String respXml="<xml>\n" +
                    "  <ToUserName><![CDATA["+map.get("FromUserName")+"]]></ToUserName>\n" +
                    "  <FromUserName><![CDATA["+map.get("ToUserName")+"]]></FromUserName>\n" +
                    "  <CreateTime>"+System.currentTimeMillis()/1000+"</CreateTime>\n" +
                    "  <MsgType><![CDATA[text]]></MsgType>\n" +
                    "  <Content><![CDATA[你好，czk的微信公众号]]></Content>\n" +
                    "</xml>";
            */
            PrintWriter writer = response.getWriter();
            String respXml = WeChatUtil.getResponse(map);
            writer.print(respXml);
            writer.flush();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/get/user")
    public String getUser(HttpServletRequest request, HttpServletResponse response) {
        // 拿到code
        String code = request.getParameter("code");
        log.info("获取未关注的用户信息进来了code{}", code);
        // 获取网页授权的AccessToken
        // 替换
        tempUserUrl = tempUserUrl.replace("APPID", appId).replace("SECRET", secret).replace("CODE", code);
        try {
            URL uRL = new URL(tempUserUrl);
            URLConnection urlConnection = uRL.openConnection();
            int len = 0;
            byte[] b = new byte[1024];
            // 读数据
            InputStream inputStream1 = urlConnection.getInputStream();
            StringBuilder resp = new StringBuilder();

            while ((len = inputStream1.read(b)) != -1) {
                resp.append(new String(b, 0, len));
            }
            String string = resp.toString();
            // 拿到token
            JSONObject jsonObject = JSONObject.parseObject(string);
            // 拿到·access_token
            String access_token = jsonObject.getString("access_token");
            // 拿到openid
            String openId = jsonObject.getString("openid");
            // 再起请求获取用户信息
            getUnLookUpUserUrl = getUnLookUpUserUrl.replace("ACCESS_TOKEN", access_token).replace("OPENID", openId);
            // 发送get请求
            URL url = new URL(getUnLookUpUserUrl);
            URLConnection urlConnection1 = url.openConnection();
            InputStream inputStream = urlConnection1.getInputStream();
            int length = 0;
            byte[] bytes = new byte[1024];
            StringBuffer buf = new StringBuffer();
            while ((length = inputStream.read(bytes)) != -1) {
                buf.append(new String(bytes, 0, length));
            }
            // 打印用户信息
            // {"openid":"o365s57rVcua532rJ9zD2US518Wk","nickname":"KD","sex":1,"language":"zh_CN","city":"自贡","province":"四川",
            // "country":"中国","headimgurl":"https:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/N2tP8qsKAnxprZzcRPh8Bw4800EgA3Z3H2ZPrcukmk2xaC1ZnxeIvJNf4LI8jYCIF2u9mkBF7fIApV8MChACHg\/132",
            // "privilege":[]}
            System.out.println(buf.toString());
            return buf.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
    @GetMapping("/get/push")
    public String getPush(){
        System.out.println("进来了");
        return "成功";
    }
}
